package linhnv.app;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class ParseXMLAccess {

	private InputStream inputStream;
	private String nameObjParse;
	private List<HashMap<String, String>> listData;
	
	/**
	 * contructor of class
	 */
	public ParseXMLAccess() {
		// TODO Auto-generated constructor stub
		listData = new ArrayList<HashMap<String,String>>();
	}
	
	/**
	 * method set source XML to parse
	 * @param inputStream (InputStream)
	 * @param nameObjParse (name of element to split)
	 */
	public void setDataSourceInputStream(InputStream inputStream, String nameObjParse)
	{
		this.inputStream = inputStream;
		this.nameObjParse = nameObjParse;
	}
	
	/**
	 * get data after proccess parseXML
	 * @return List<HashMap<String, String>>
	 */
	public List<HashMap<String, String>> getData()
	{
		try {

			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader*/ 
			PaseXMLHandler handler;
			
			handler = new PaseXMLHandler(nameObjParse);
			
			xr.setContentHandler(handler);
			
			// For TEST
			//testData();
			
			/* set source parse */
			xr.parse(new InputSource(this.inputStream));
			
			/* get data after parse. */
			listData = handler.getData();
			
			return listData;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			
			Log.e("ParseXMLAccess", "getData with exception " + e.getLocalizedMessage());
			
			return null;
		}
	}
	
//	private void testData(){
//		String text = "<WGT Name='360°回転サンプル' ID='A300003' File='./360b.wgt' Revision='1' UpdateMsg='false'>" +
//	     "<WidgetsProgressbar msg='読み込み中..(%s)'/><PageWidgets>" +
//	     "<PageWidget Location='1' Data='http://studio88.jp/sm_ext/single_tst/dress2/widget/dress2.wgt' Enc='112C362A2E0262596D54' Revision='2'/>" +
//	         "</PageWidgets></WGT>";
//	   
//		try {
//		   inputStream = new ByteArrayInputStream(text.getBytes("UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	
}
